package com.shxzz.shortlink.project.service.impl;

import com.shxzz.shortlink.project.common.convention.exception.ServiceException;
import com.shxzz.shortlink.project.service.UrlInfoService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;

/**
 * @author shxzz
 * @create 2023-12-21-16:13
 * @description 目标网址信息获取服务接口实现层
 */
@Service
public class UrlInfoServiceImpl implements UrlInfoService {
    @Override
    public String getTargetUrlTitle(String targetUrl) {

        Document doc = null;
        try {
            URL url = new URL(targetUrl);
            doc = Jsoup.parse(url, 3000);
        } catch (IOException e) {
            throw new ServiceException("目标网站标题获取失败");
        }
        return doc.title();
    }

    @Override
    public String getTargetUrlFavicon(String targetUrl) {
        Document doc = null;
        try {
            URL url = new URL(targetUrl);
            doc = Jsoup.parse(url, 3000);
        } catch (IOException e) {
            throw new ServiceException("目标网站图标获取失败");
        }
        return doc.select("link[rel='shortcut icon']").attr("href");
    }
}
